<?php
/**
 * 添加角色
 * User: cxm
 * Date: 2019/10/24
 * Time: 10:25
 */
namespace App\Http\Controllers\Admin\AdminUser;
use App\Http\Controllers\Admin\Controller;
use App\Models\AdminPermission;
use App\Models\AdminRole;
use App\Models\AdminRolePermission;
use App\Models\AdminUserRole;
use App\Models\Auth;
use App\Models\File;
use App\Models\RoleAuth;
use Carbon\Carbon;
use DB,Validator;
use Illuminate\Http\Request;

class RoleController extends Controller {
    /**
     * 添加、编辑处理
     * URL POST:/admin/role/store
     * @param Request $request
     * @param int id 角色ID 编辑时传
     * @param string name 角色名称
     * @param string desc 角色介绍
     * @param array permission 权限[1,2,3,4]
     * @return mixed
     * @throws
     */
    public function store(Request $request){
        $params = $request->only(['id','name','desc','permission']);
        $id = isset($params['id']) ? $params['id'] : 0;
        $validator = Validator::make($params,[
            'name'      => ['required'],
            'permission'=>['array']
        ],[
            'name.required' => '角色名称不能为空',
            'permission.array' => '请选择权限'
        ]);
        if ($validator->fails()) {
            return $this->error($validator->errors()->first());
        }
        if ($id == 0) {
            $role = new AdminRole();
        }else{
            $role = AdminRole::find($id);
            if (!$role) {
                return $this->error('角色不存在');
            }
        }
        $admin_id = $this->userId();
        DB::beginTransaction();
        try{
            $role->name             = $params['name'];
            $role->desc             = isset($params['desc']) ? $params['desc'] : '';
            if ($role->save()) {
                if ($params['permission']) {
                    // 删除原有的权限
                    AdminRolePermission::where('role_id',$role->id)->forceDelete();
                    // 查看父ID是否在数组内
                    $parentIds = AdminPermission::getParentIds($params['permission']);
                    $parentIds = array_diff($parentIds, [0]);
                    $data = [];
                    foreach ($parentIds as $item) {
                        $data[] = [
                            'role_id'       => $role->id,
                            'permission_id' => $item,
                            'created_at'    => Carbon::now(),
                            'updated_at'    => Carbon::now()
                        ];
                    }
                    AdminRolePermission::insert($data);
                }else{
                    // 删除原有的权限
                    AdminRolePermission::where('role_id',$role->id)->forceDelete();
                }
            }
            DB::commit();
        }catch (\Exception $e){
            DB::rollBack();
            return $this->error($e->getMessage());
        }
        return $this->success('添加成功',[$role->id]);
    }

    /**
     * 获取角色列表
     * URL GET:/admin/role/get-lists
     * @param Request $request
     * @param string keyword 关键字
     * @param int page 页码
     * @param int limit 每页显示条数
     * @return mixed
     */
    public function getLists(Request $request){
        $params = $request->only(['keyword','page','limit']);
        $where = [];
        if(!empty($params['keyword'])){
            $where[] = ['name','like','%'.$params['keyword'].'%'];
        }
//        $where[] = ['id','!=',1];
        $page = isset($params['page']) ? $params['page'] : 1;
        $limit = isset($params['limit']) ? $params['limit'] : config('exam.pageSize');
        $data = AdminRole::getData($where,[],$page,$limit);
        return $this->success('查询成功',$data);
    }

    /**
     * 角色详情
     * URL GET:/admin/role/detail
     * @param Request $request
     * @param int role_id 角色ID
     * @return mixed
     */
    public function detail(Request $request){
        $params = $request->only(['role_id']);
        if (!array_key_exists('role_id',$params) || empty($params['role_id'])) {
            return $this->error('缺少角色ID');
        }
        $role_id = $params['role_id'];

        $where = [];
        $where[] = ['id',$role_id];
        $detail = AdminRole::detail($where);
        if ($detail) {
            $detail = $detail->toArray();
            $admin = AdminUserRole::where([['role_id', $detail['id']]])->get(['user_id'])->toArray();
            if ($admin) {
                foreach ($admin as $index => $val) {
                    $detail['user_id'][] = $val['user_id'];
                }
            }
            $menu = AdminRolePermission::where([['role_id', $detail['id']]])->orderBy('permission_id')->get(['permission_id'])->toArray();
            if ($menu) {
                foreach ($menu as $k => $v) {
                    $detail['permission'][] = $v['permission_id'];
                }
            }
        }
        return $this->success('查询成功',$detail);
    }

    /**
     * 删除角色
     * URL POST:/admin/role/delete
     * @param Request $request
     * @param array ids 角色ID
     * @return mixed
     */
    public function delete(Request $request){
        $params = $request->only(['ids']);
        if (!array_key_exists('ids',$params)){
            return $this->error('缺少角色ID');
        }
        $result = AdminRole::whereIn('id',$params['ids'])->delete();
        if (!$result) {
            return $this->error('删除失败');
        }else{
            return $this->success('删除成功');
        }
    }
}